//
//  LoginVC.m
//  WoWeiRenRenOC
//
//  Created by 姜孟东 on 2020/3/13.
//  Copyright © 2020 姜孟东. All rights reserved.
//

#import "LoginVC.h"
#import "WRBaseButton.h"
#import "BannerModel.h"
#import "BaseTabBarController.h"
#import "RegisterVC.h"
#import "HomeDataModel.h"
#import "ServiceInfoVC.h"
#import "WebVC.h"
#import "NewFillInInformationTableVC.h"
#import "VIPRightShowView.h"
#import "FuWuWebVC.h"

@interface LoginVC ()<SDCycleScrollViewDelegate,UITextViewDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *top;
@property (weak, nonatomic) IBOutlet UILabel *membersLabel;
@property (weak, nonatomic) IBOutlet UILabel *merchantsLabel;
@property (weak, nonatomic) IBOutlet UIImageView *oneBg;
@property (weak, nonatomic) IBOutlet UIImageView *twoBg;
@property (assign, nonatomic)BOOL isMerchants;
@property (weak, nonatomic) IBOutlet UIButton *registerBtn;
@property (weak, nonatomic) IBOutlet UIButton *lookPasswordBtn;
@property (weak, nonatomic) IBOutlet UIButton *forgetBtn;
@property (weak, nonatomic) IBOutlet WRBaseButton *loginBtn;
@property (weak, nonatomic) IBOutlet UITextField *accountTF;
@property (weak, nonatomic) IBOutlet UITextField *passwordTF;
@property (weak, nonatomic) IBOutlet UILabel *userCountLabel;
@property (weak, nonatomic) IBOutlet UIView *headImageBgView;
@property (nonatomic, strong) SDCycleScrollView *cycleScrollView;
@property (strong, nonatomic)NSMutableArray *bannerImageArray;
@property (strong, nonatomic)NSMutableArray *bannerArray;

@property (strong, nonatomic)HomeDataModel *homeDataModel;
@property (weak, nonatomic) IBOutlet UIView *bottomBannerBg;
@property (nonatomic, strong) SDCycleScrollView *bottomCycleScrollView;
@property (strong, nonatomic)NSMutableArray *bottomBannerImageArray;
@property (strong, nonatomic)NSMutableArray *bottomBannerArray;
@property (weak, nonatomic) IBOutlet UITextView *serviceTF;

@property (weak, nonatomic) IBOutlet UIButton *serviceBtn;

@end

@implementation LoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
   
    
    [self setUi];
    [self queryBanner];
    [self queryBottomBanner];
    [self queryTj];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setHidden:YES];
    
    
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setHidden:NO];
    
    
}


- (void)setUi {
    
    if (NeediPhoneXiPhoneXR) {
           self.top.constant = NEW_StatusBarHeight;
    }
    
    
    
    UITapGestureRecognizer *oneTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(oneTap)];
    [self.membersLabel addGestureRecognizer:oneTap];
    
    UITapGestureRecognizer *twoTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(twoTap)];
    [self.merchantsLabel addGestureRecognizer:twoTap];
    
    [self.lookPasswordBtn addTarget:self action:@selector(lookPasswordBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.loginBtn addTarget:self action:@selector(loginBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.registerBtn addTarget:self action:@selector(registerBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.forgetBtn addTarget:self action:@selector(forgetBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    self.cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, KSCREEN_WIDTH, 140) delegate:self placeholderImage: kImageNamed(@"default_image_square")];
        /**设置自动滚动时间间隔 */
    self.cycleScrollView.autoScrollTimeInterval = 2;
    self.cycleScrollView.autoScroll = YES;
    self.cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    self.cycleScrollView.showPageControl = YES;
    self.cycleScrollView.delegate = self;
    [self.headImageBgView addSubview:self.cycleScrollView];
    
    self.cycleScrollView.localizationImageNamesGroup = @[@"default_image_square",@"default_image_square"];
    
    self.bottomCycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, KSCREEN_WIDTH-20, 80) delegate:self placeholderImage: kImageNamed(@"default_image_square")];
        /**设置自动滚动时间间隔 */
    self.bottomCycleScrollView.autoScrollTimeInterval = 2;
    self.bottomCycleScrollView.autoScroll = YES;
    self.bottomCycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    self.bottomCycleScrollView.showPageControl = YES;
    self.bottomCycleScrollView.delegate = self;
    [self.bottomBannerBg addSubview:self.bottomCycleScrollView];
    
    self.bottomCycleScrollView.localizationImageNamesGroup = @[@"default_image_square",@"default_image_square"];
    
    self.bottomBannerBg.layer.cornerRadius = 40;
    self.bottomBannerBg.clipsToBounds = YES;
    
    self.serviceTF.editable = NO;
    self.serviceTF.delegate = self;
    //设置添加链接部分文字的颜色，即“《XXX隐私政策》”
    self.serviceTF.linkTextAttributes = @{NSForegroundColorAttributeName:[UIColor colorWithRed:0.87 green:0.66 blue:0.28 alpha:1],NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle)};
    
    
    NSString *rangeStr = @"服务条款和隐私政策";
    NSString *protocolStr = [NSString stringWithFormat:@"阅读并同意 %@",rangeStr];
    NSRange privacyRange = [protocolStr rangeOfString:rangeStr];
    NSMutableAttributedString *privacyMutableAttrStr = [[NSMutableAttributedString alloc] initWithString:protocolStr attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14.0],NSForegroundColorAttributeName:kRGBColor(11, 11, 11)}];
    
    //给需要 点击事件的部分添加链接
    [privacyMutableAttrStr addAttribute:NSLinkAttributeName value:@"privacy://" range:privacyRange];
    self.serviceTF.attributedText = privacyMutableAttrStr;
    
}

- (void)forgetBtnClick {
    
    UIAlertController *alterController = [UIAlertController alertControllerWithTitle:nil message:@"是否联系客服电话修改密码？" preferredStyle:UIAlertControllerStyleAlert];
    
    [alterController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [alterController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [CommonTTool serviceCallPhone];
    }]];
    
    [self presentViewController:alterController animated:YES completion:nil];
    
}


#pragma mark - UITextViewDelegate
-(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange{
    if ([URL.scheme isEqualToString:@"privacy"]) {
        //这里调用方法跳到隐私政策页面
//        ServiceInfoVC *vc = [[ServiceInfoVC alloc]init];
//        [self.navigationController pushViewController:vc animated:YES];
//        return NO;
        FuWuWebVC *vc = [[FuWuWebVC alloc]init];
        vc.title = @"服务条款";
        vc.linkPath = [[NSBundle mainBundle] pathForResource:@"服务条款-更新.docx" ofType:nil];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    return YES;
}

- (IBAction)serviceBtnClick:(id)sender {
    
    self.serviceBtn.selected = !self.serviceBtn.isSelected;
    
    if (self.serviceBtn.selected) {
        
        [self.serviceBtn setImage:[UIImage imageNamed:@"gouxuan_on"] forState:UIControlStateNormal];
        
    }else{
        
        [self.serviceBtn setImage:[UIImage imageNamed:@"gouxuan_off"] forState:UIControlStateNormal];
        
    }
}



- (void)oneTap {
    
    self.oneBg.hidden = NO;
    self.twoBg.hidden = YES;
    self.isMerchants = NO;
    self.registerBtn.hidden = NO;
    [self setUserCount];
    [self queryBanner];
    [self queryBottomBanner];
//    self.userCountLabel.hidden = YES;
}

- (void)twoTap {
    
    self.oneBg.hidden = YES;
    self.twoBg.hidden = NO;
    self.isMerchants = YES;
    self.registerBtn.hidden = YES;
    [self setUserCount];
    [self queryBanner];
    [self queryBottomBanner];
//    self.userCountLabel.hidden = NO;
}


- (void)registerBtnClick {
    
//    NewFillInInformationTableVC *vc = [[NewFillInInformationTableVC alloc]init];
//
//     [self.navigationController pushViewController:vc animated:YES];
    RegisterVC *vc = [[RegisterVC alloc]initWithNibName:@"RegisterVC" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
    
    
}

- (void)loginBtnClick {
    

    
    if (self.isMerchants) {
        
        [self merchantsLogin];
        
    }else {
        [self userLogin];
        
    }
    
    
}

- (void)merchantsLogin {
    
    
    if (!self.serviceBtn.selected) {
        
        SVP(@"请阅读并同意服务条款和隐私政策");
        return;
    }
    
    NSString *name = self.accountTF.text;
    NSString *password = self.passwordTF.text;
    if ([CommonTTool isStrNull:name]) {
        SVP(@"请输入您的账号")
        return;
    }
    if ([CommonTTool isStrNull:password]) {
        SVP(@"请输入您的密码")
        return;
    }
    
    SVPShowInternetWaiting
    [NetManager isMerchantsLoginWithParameters:@{@"phone":name,@"password":password} success:^{
        
        SVP(@"登录成功");
        dispatch_async(dispatch_get_main_queue(), ^{
            // 记录是否是商户
            [[NSUserDefaults standardUserDefaults] setBool:self.isMerchants forKey:@"kUserIsMerchants"];
            
            BaseTabBarController *baseTabBar = [[BaseTabBarController alloc]init];
            AppDelegate *delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
            baseTabBar.selectedIndex = 0;
            delegate.window.rootViewController = baseTabBar;
        });
        
        
    }];
    
    
    
}


- (void)userLogin {
    
    if (!self.serviceBtn.selected) {
        
        SVP(@"请阅读并同意服务条款和隐私政策");
        return;
    }
    
    NSString *name = self.accountTF.text;
    NSString *password = self.passwordTF.text;
    if ([CommonTTool isStrNull:name]) {
        SVP(@"请输入您的账号")
        return;
    }
    if ([CommonTTool isStrNull:password]) {
        SVP(@"请输入您的密码")
        return;
    }
    
    SVPShowInternetWaiting
    [NetManager isLoginWithParameters:@{@"username":name,@"password":password} success:^{
        
        SVP(@"登录成功");
        dispatch_async(dispatch_get_main_queue(), ^{
            // 记录是否是商户
            [[NSUserDefaults standardUserDefaults] setBool:self.isMerchants forKey:@"kUserIsMerchants"];
            
            BaseTabBarController *baseTabBar = [[BaseTabBarController alloc]init];
            AppDelegate *delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
            baseTabBar.selectedIndex = 0;
            delegate.window.rootViewController = baseTabBar;
        });
        
        
    }];
    
    
}


- (void)lookPasswordBtnClick:(UIButton *)btn {
    
    btn.selected = !btn.isSelected;
    if (btn.selected) {
        
        [btn setImage:[UIImage imageNamed:@"zhengyan_on"] forState:UIControlStateNormal];
        self.passwordTF.secureTextEntry = NO;
    }else{
        
        [btn setImage:[UIImage imageNamed:@"zhengyan_off"] forState:UIControlStateNormal];
        self.passwordTF.secureTextEntry = YES;
    }
    
    
}


- (void)queryTj {
    
    [NetManager isQueryTjWithParameters:@{} success:^(NSDictionary * _Nonnull dic) {
        
        self.homeDataModel = [HomeDataModel mj_objectWithKeyValues:dic[@"object"]];
        [self setUserCount];
    } finish:^{
        
    }];
    
    
}


- (void)setUserCount {
    
    if (self.isMerchants) {
        
        int total = [self.homeDataModel.xn_business_count intValue] + [self.homeDataModel.business_count intValue];
        
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"已入驻商家数:%d",total]];
        
        [string addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:0.87 green:0.66 blue:0.28 alpha:1] range:NSMakeRange(7,string.length-7)];
        
        self.userCountLabel.attributedText = string;
        
    }else {
        int total = [self.homeDataModel.xn_user_count intValue] + [self.homeDataModel.user_count intValue];
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"已注册会员数:%d",total]];
        
        [string addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:0.87 green:0.66 blue:0.28 alpha:1] range:NSMakeRange(7,string.length-7)];
        
        self.userCountLabel.attributedText = string;
    }
    
    
    
    
}

- (void)queryBanner {
    
    NSString *url = @"USER_LOGIN_TOP";
    if (self.isMerchants) {
        url = @"BUS_LOGIN_TOP";
    }
    
    [NetManager isBannerinfoListWithParameters:@{@"position":url} success:^(NSDictionary * _Nonnull dic) {
        
        self.bannerArray = [BannerModel mj_objectArrayWithKeyValuesArray:dic[@"object"]];
        self.bannerImageArray = [NSMutableArray array];
        for (BannerModel *model in self.bannerArray) {
            
            [self.bannerImageArray addObject:model.img_path];
            
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            self.cycleScrollView.imageURLStringsGroup = self.bannerImageArray;
            
        });
        
    } finish:^{
        
    }];
    
    
    
}


- (void)queryBottomBanner {
    
    NSString *url = @"USER_LOGIN_BOTTOM";
    if (self.isMerchants) {
        url = @"BUS_LOGIN_BOTTOM";
    }
    
    [NetManager isBannerinfoListWithParameters:@{@"position":url} success:^(NSDictionary * _Nonnull dic) {
        
        self.bottomBannerArray = [BannerModel mj_objectArrayWithKeyValuesArray:dic[@"object"]];
        self.bottomBannerImageArray = [NSMutableArray array];
        for (BannerModel *model in self.bottomBannerArray) {
            
            [self.bottomBannerImageArray addObject:model.img_path];
            
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            self.bottomCycleScrollView.imageURLStringsGroup = self.bottomBannerImageArray;
            
        });
        
    } finish:^{
        
    }];
    
    
    
}

/** 点击图片回调 */
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    
    if (cycleScrollView == self.cycleScrollView) {
            
        BannerModel *model = self.bannerArray[index];
        if ([model.jump_type isEqualToString:@"0"]) {
            
            WebVC *vc = [[WebVC alloc]init];
            vc.webtitle  = model.title;
            vc.linkPath = model.jump_path;
            vc.htmlString = model.depict;
            [self.navigationController pushViewController:vc animated:YES];
        }
        
        
    }else {
        
        BannerModel *model = self.bottomBannerArray[index];
        if ([model.jump_type isEqualToString:@"0"]) {
            
            WebVC *vc = [[WebVC alloc]init];
            vc.webtitle  = model.title;
            vc.linkPath = model.jump_path;
            vc.htmlString = model.depict;
            [self.navigationController pushViewController:vc animated:YES];
        }
        
        
    }
    
    
}

@end
